<?php

namespace app\modules\admin\controllers;
error_reporting(0);
use app\models\ActiveMqApi;
use app\models\Storage;
use app\models\Api;
use app\models\Card;
use app\models\CardImportForm;
use app\models\SysProvinces;
use app\models\Isp;
use app\models\KeyMap;
use app\models\ManagerLog;
use app\models\PackageIsp;
use app\models\Ruku;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use Yii;
use yii\base\InvalidConfigException;
use yii\data\Pagination;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;

/**
 * 入库管理
 * Class CardController
 * @package app\modules\admin\controllers
 */
class StorageController extends BaseController
{
    /**
     * 入库列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionList()
    {

        $query = Storage::find()->alias('storage');
        $query->andFilterWhere(['storage.order' => $this->get('search_order')]);
        $query->andFilterWhere(['storage.pur_name' => $this->get('search_name')]);
        if(!$this->get('search_time')){
            $query->andFilterWhere(['storage.pur_time'=> '']);
        }else{
           $query->andFilterWhere(['storage.pur_time' => strtotime($this->get('search_time'))]); 
        } 
        $query->andFilterWhere(['storage.payment_type' => $this->get('search_status')]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy(['id'=>SORT_DESC]);
        $query->offset($pagination->offset)->limit($pagination->limit);
        if ($this->get('export') == 'excel') { // 导出Excel文件
            try {
                $excel = new Spreadsheet();
                $sheet = $excel->setActiveSheetIndex(0);
                foreach ([
                             '编号',
                             '采购时间',
                             '名称',
                             '订单号',
                             '运营商',
                             '套餐',
                             '采购数量',
                             '卡类型',
                             '沉默期到期时间',
                             '沉默期时长(月)',
                             '单价',
                             '总价',
                             '付款类型',
                             '单卡预存时长',
                             '创建时间',
                         ] as $index => $title) {
                    $sheet->setCellValue(chr(65 + $index) . '1', $title);
                }
                $sheet->getStyle('A1:Z1')->applyFromArray(['font' => ['bold' => true], 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER]]);
                $r = 2;
                /** @var Card $card */
                foreach ($query->each() as $storage) {
                    $sheet->setCellValueExplicitByColumnAndRow(1, $r, $storage->id, DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(2, $r, Yii::$app->formatter->asDate($storage->pur_time),DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(3, $r, $storage->pur_name,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(4, $r, $storage->order,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(5, $r, empty($storage->isp_id) ? '' :$storage->isp->name, DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(6, $r, empty($storage->package_id) ? '' : $storage->packageIsp->name, DataType::TYPE_STRING);  
                    $sheet->setCellValueExplicitByColumnAndRow(7, $r, $storage->number,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(8, $r, empty($storage->simtype) ? '' : $storage->type->name, DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(9, $r, Yii::$app->formatter->asDate($storage->silent_over),DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(10,$r, $storage->silent_time, DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(11,$r, $storage->price, DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(12,$r, $storage->total_price,DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(13,$r, KeyMap::getValue('payment_type',$storage->payment_type),DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(14,$r, $storage->pre_time,DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(15,$r, Yii::$app->formatter->asDatetime($storage->create_time),DataType::TYPE_STRING);
                    $r++;
                }
                $sheet->freezePane('A2');

                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="采购入库单_' . date('Y-m-d') . '.xls"');
                header('Cache-Control: max-age=0');
                $excelWriter = IOFactory::createWriter($excel, 'Xls');
                $excelWriter->save('php://output');
            } catch (\Exception $e) {
                Yii::error('导出Excel文件时出错：' . $e->getMessage());
                Yii::error($e->getTraceAsString());
                echo $e->getMessage();
            }
            die();
        }
        $storageList = $query->all();
        return $this->render('list', [
            'storageList' => $storageList,
            'pagination' => $pagination,
        ]);
    }

    //新增采购入库单
    public function actionEdit(){
        $api = Yii::$app->request->post('Storage','isp_id');
        $id = $api['isp_id'];
        $model = ISP::find()->where(['id' => $id])->one();
        $card = new Storage();
        $card->order = date('Ymd').time();
        $card->create_time = time();
        $card->api_id = $model->api_id;
        if ($card->load($this->post()) && $card->save()) {
            ManagerLog::info($this->manager->id, '保存入库单', print_r($card->attributes, true));
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['/admin/storage/list']),
                'txt' => '入库管理列表'
            ]));
        }
        return $this->render('edit', [
            'card' => $card,
        ]);
    }
    //获取套餐价格
    public function actionPackageprice()
    {

        $id = $this->get('id');
        $model = PackageIsp::findOne(['id' => $id])->toArray();
        return [
            'code'=>'1',
            'data'=>$model
        ];

    }
    //入库单详情
    public function actionStorageView(){
        $id = $this->get('id');
        $storage = Storage::findOne(['id' => $id]);
        return $this->render('storage_view', [
            'storage' => $storage,
        ]);
    }
   
   //修改入库单
    public function actionModify(){
        $id = $this->get('id');
        $modify = Storage::findOne(['id' => $id]);   
        $isp_id = $modify['isp_id'];
        $model = Isp::findOne(['id'=>$isp_id]);
        $modify->api_id = $model->api_id;    
        if ($modify->load($this->post()) && $modify->save()) {
            ManagerLog::info($this->manager->id, '保存入库单', print_r($modify->attributes, true));
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['/admin/storage/list']),
                'txt' => '入库管理列表'
            ]));
        }
        return $this->render('modify',[
            'modify'  => $modify,
        ]);
    }
    //删除入库单
    public function actionDeleteOrder(){
        $id = $this->get('id');
        $model = Storage::findOne(['id' => $id]);
        if(empty($model)){
            return [
                'message'=>'没有找到入库单信息'
            ];
        }
        try {
            $model->delete();
        } catch (\Throwable $e){
        }
        ManagerLog::info($this->manager->id,'删除入库单',print_r($model->attributes,true));
        $this->redirect(['/admin/storage/list']);
    }
    //入库订单
    public function actionOrder(){
        $query = Ruku::find()->alias('ruku');
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy(['id'=>SORT_DESC]);
        $query->andFilterWhere(['ruku.rkorder' => $this->get('search_order')]);
        $query->andFilterWhere(['ruku.rk_name' => $this->get('search_name')]);
        $starttime = strtotime($this->get('search_time'));
        $endtime = $starttime + '86399';
        if(!$this->get('search_time')){
            $query->andFilterWhere(['ruku.rk_time'=> '']);
        }else{
           $query->andFilterWhere(['between','ruku.rk_time',$starttime,$endtime]);
        } 
        $query->andFilterWhere(['ruku.import_status'=> $this->get('search_status')]);
        $query->offset($pagination->offset)->limit($pagination->limit);
        if ($this->get('export') == 'excel') { // 导出Excel文件
            try {
                $excel = new Spreadsheet();
                $sheet = $excel->setActiveSheetIndex(0);
                foreach ([
                             '编号',
                             '订单号',
                             '名称',
                             '时间',
                             '运营商',
                             '套餐',
                             '采购数量',
                             'iccid开始',
                             'iccid结束',
                             'iccid列表',
                             '单价',
                             '总价',
                             '导入状态',
                         ] as $index => $title) {
                    $sheet->setCellValue(chr(65 + $index) . '1', $title);
                }
                $sheet->getStyle('A1:Z1')->applyFromArray(['font' => ['bold' => true], 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER]]);
                $r = 2;
                /** @var Card $card */
                foreach ($query->each() as $order) {
                    $sheet->setCellValueExplicitByColumnAndRow(1, $r, $order->id, DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(2, $r, $order->rkorder,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(3, $r, $order->rk_name,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(4, $r, Yii::$app->formatter->asDatetime($order->rk_time),DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(5, $r, empty($order->isp_id) ? '-' :$order->isp->name, DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(6, $r, empty($order->package_id) ? '-' : $order->packageIsp->name, DataType::TYPE_STRING);  
                    $sheet->setCellValueExplicitByColumnAndRow(7, $r, $order->number,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(8, $r, empty($order->iccid_start) ? '--' : $order->iccid_start,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(9, $r, empty($order->iccid_end) ? '--' : $order->iccid_end,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(10,$r, empty($order->iccid_list) ? '--' : $order->iccid_list,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(11,$r, $order->price,DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(12,$r, $order->total_price,DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(13,$r, KeyMap::getValue('import_status',$order->import_status),DataType::TYPE_STRING);
                    $r++;
                }
                $sheet->freezePane('A2');

                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="入库订单_' . date('Y-m-d') . '.xls"');
                header('Cache-Control: max-age=0');
                $excelWriter = IOFactory::createWriter($excel, 'Xls');
                $excelWriter->save('php://output');
            } catch (\Exception $e) {
                Yii::error('导出Excel文件时出错：' . $e->getMessage());
                Yii::error($e->getTraceAsString());
                echo $e->getMessage();
            }
            die();
        }
        $orderList = $query->all();
        return $this->render('order_list',[
            'orderList'  => $orderList,
            'pagination' => $pagination,
        ]);
        
    }

    //新增入库订单
    public function actionOrderEdit(){

       $orderedit = new Ruku();
       $aa = Yii::$app->request->post('Ruku','rkd');
       $id = $aa['rkd'];
       $order = Storage::find()->where(['id' => $id])->one();
       $orderedit->batch_no = Storage::generateBatchNo($this->manager->id);
       $orderedit->rkorder = date('Ymd').time();
       $orderedit->api_id = $order->api_id;
       $orderedit->isp_id = $order->isp_id;
       $orderedit->package_id = $order->package_id;
       $orderedit->number = $order->number;
       $orderedit->price = $order->price;
       $orderedit->total_price = $order->total_price;
       $orderedit->rk_time = time();    
       if ($orderedit->load($this->post()) && $orderedit->save()) {
            ManagerLog::info($this->manager->id, '操作完成', print_r($orderedit->attributes, true));
            Yii::$app->db->createCommand()->update('storage', ['status' => 1], 'id = :id',['id' => $id])->execute();  
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['/admin/storage/order']),
                'txt' => '订单'
            ]));
        }
        
        return $this->render('order_edit',[
            'orderedit' => $orderedit,
        ]);
        
    }
    //修改入库订单
    public function actionOrderModify(){
        $id = $this->get('id');
        $modify = Ruku::findOne(['id' => $id]);    
        if ($modify->load($this->post()) && $modify->save()) {
            ManagerLog::info($this->manager->id, '保存入库订单', print_r($modify->attributes, true));
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['/admin/storage/order']),
                'txt' => '入库订单列表'
            ]));
        }
        return $this->render('order_modify',[
            'modify' => $modify,
        ]);
    }
    //删除入库单
    public function actionDeleteOrderList(){
        $id = $this->get('id');
        $model = Ruku::findOne(['id' => $id]);
        $status = $model->import_status;
        $rkd = $model->rkd;
        if(empty($model)){
            return [
                'message'=>'没有找到订单信息'
            ];
        }
        try {
            $model->delete();
        } catch (\Throwable $e){
        }
        if($status == '0'){
            Yii::$app->db->createCommand()->update('storage', ['status' => 0], 'id = :id',['id' => $rkd])->execute();  
        }
        ManagerLog::info($this->manager->id,'删除入库订单',print_r($model->attributes,true));
        $this->redirect(['/admin/storage/order']);
    }
    //导入卡
    public function actionOrderImport(){
        $id = $this->get('id');
        $model = new CardImportForm();
        $modify = Ruku::find()->where(['id' => $id])->one();
        $model->iccid_start = $modify['iccid_start'];
        $model->iccid_end = $modify['iccid_end'];
        $model->iccid_list = $modify['iccid_list'];
        $model->batch_no = $modify['batch_no'];
        $model->api_id = $modify['api_id'];
        $model->isp_id = $modify['isp_id'];
        $model->package_isp_id = $modify['package_id'];
        if ($model->load($this->post()) && $model->import($this->manager->id)) {
            ManagerLog::info($this->manager->id, '导入卡', print_r($model->attributes, true));
            Yii::$app->db->createCommand()->update('ruku', ['import_status' => 1], 'id = :id',['id' => $id])->execute(); 
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['/admin/storage/order']),
                'txt' => '入库订单列表'
            ]));
        }
        return $this->render('order_import',[
            'modify' => $modify,
            'model'  => $model
        ]);
    }
    //入库订单详情
    public function actionOrderView(){
        $id = $this->get('id');
        $order = Ruku::findOne(['id'=>$id]);
        return $this->render('order_view',[
            'order' => $order,
        ]);
    }

   
}
